package main

import (
	"fmt"
	"io/ioutil"
	"iot-base/common/monitorprocess"
	"log"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/kardianos/service"
	"golang.org/x/text/encoding/simplifiedchinese"
)

type program struct{}

func (p *program) Start(s service.Service) error {
	go p.run()
	return nil
}

func killAll() {
	monitorprocess.KillAll(false)
	// fmt.Println("kill devProvider")
	// cmdr1 := exec.Command("sc", "stop", "DevProvider")
	// cmdr1.Run()
	// time.Sleep(2 * time.Second)
	// fmt.Println("restart devProvider")
	cmdr2 := exec.Command("sc", "start", "DevProvider")
	cmdr2.Run()

	// fmt.Println("kill redis")
	// cmdr3 := exec.Command("sc", "stop", "Redis")
	// cmdr3.Run()
	// time.Sleep(2 * time.Second)
	// cmdr4 := exec.Command("sc", "start", "Redis")
	// cmdr4.Run()
	// fmt.Println("restart redis")

}

func (p *program) run() {
	time.Sleep(30 * time.Second)
	for {
		if isCheck {
			timeout := time.Duration(3) * time.Second
			client := http.Client{
				Timeout: timeout,
			}

			resp, err := client.Get("http://127.0.0.1:18866/others/tryHeart")
			if resp != nil && err == nil {

				body, err := ioutil.ReadAll(resp.Body)
				if err == nil {
					sbody := string(body)
					if !strings.Contains(sbody, "endless world") {
						killAll()
					}
				} else {
					killAll()
				}
				resp.Body.Close()

			} else {
				killAll()
			}
			fmt.Println("---------monitor-----------")
			monitorprocess.Run()
		}

		time.Sleep(time.Second * 120)

	}
}

func (p *program) Stop(s service.Service) error {
	monitorprocess.KillAll(true)
	return nil
}

func init() {

}

var isCheck = true
var port = "18889"

func beginHttpServer() {
	r := gin.Default()
	m := r.Group("/m/api/")
	{
		m.GET("cmd/:cmdname", func(c *gin.Context) {
			cmdname := c.Param("cmdname")
			if cmdname == "" {
				c.String(http.StatusOK, "参数为空，不能运行")
			}
			params := c.Query("params")
			path := c.Query("path")
			var paramsArgs []string
			if params != "" {
				paramsArgs = strings.Split(params, " ")

			}
			if path != "" {
				cmdname = path + "\\" + cmdname
			}

			cmd := exec.Command(cmdname, paramsArgs...)
			out, err := cmd.CombinedOutput()
			scmd := fmt.Sprint(cmdname, paramsArgs)

			bout, _ := simplifiedchinese.GBK.NewDecoder().Bytes(out)
			sout := string(bout)
			if err != nil {
				//fmt.Printf("combined out:\n%s\n", string(out))
				c.String(http.StatusOK, "error:"+err.Error()+" "+scmd+"  out:"+sout)
				return
			}
			c.String(http.StatusOK, scmd+"  out:"+sout)

		})
		m.GET("stopmonitor", func(c *gin.Context) {
			isCheck = false
			c.String(http.StatusOK, "OK")
		})
		m.GET("startmonitor", func(c *gin.Context) {
			isCheck = true
			c.String(http.StatusOK, "OK")
		})
		m.GET("list", func(c *gin.Context) {
			c.String(http.StatusOK, "startmonitor stopmonitor cmd(cmdname?params=XXX)")
		})
	}
	r.Run(":" + port)
}

func main() {
	svcConfig := &service.Config{
		Name:        "BOXService",
		DisplayName: "BOXService",
		Description: "windows service for boxes",
	}

	prg := &program{}
	s, _ := service.New(prg, svcConfig)

	if len(os.Args) > 1 {
		fmt.Println("-------------*************----000001--", os.Args[1])
		if os.Args[1] == "install" {
			//s.Install()
			cmd := exec.Command("sc", "create", "BOXService", `binPath= "`+monitorprocess.GetPWD()+"/s.exe"+`"`, "start= auto")
			out, err := cmd.CombinedOutput()
			log.Println("服务安装", string(out), err)
			fmt.Println("**************************************")
			cmdr := exec.Command("sc", "start", "BOXService")
			cmdr.Run()

			return
		}

		if os.Args[1] == "remove" {

			monitorprocess.KillAll(true)
			cmd := exec.Command("sc", "stop", "BOXService")
			cmd.Run()
			s.Uninstall()
			log.Println("服务卸载成功")
			return
		}
	}

	go beginHttpServer()
	if err := s.Run(); err != nil {
		log.Panicln(err)
	}
}
